using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Text;

namespace Crainiate.Data.Persistence
{
    [Serializable]
    public class Relationship: IRelationship, ISerializable, IDeserializationCallback
    {
        //Property variables
        private List<IPersistable> _parents;
        private List<IPersistable> _children;
        private IPersistable _result;

        //Working variables
        private SerializationInfo mInfo;

        //Constructors
        public Relationship(IPersistable result)
        {
            if (result == null) throw new ArgumentException("The result passed to the constructor may not be null.");
            _parents = new List<IPersistable>();
            _children = new List<IPersistable>();
            _result = result;
        }

        protected Relationship(SerializationInfo info, StreamingContext context)
        {
            _parents = new List<IPersistable>();
            _children = new List<IPersistable>();
            mInfo = info;
        }

        //Properties
        public IList<IPersistable> Parents
        {
            get 
            { 
                return _parents; 
            }
        }

        public IList<IPersistable> Children
        {
            get 
            { 
                return _children; 
            }
        }

        public IPersistable Result
        {
            get
            {
                return _result;
            }
        }

        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Parents",_parents.ToArray());
            info.AddValue("Children",_children.ToArray());
            info.AddValue("Result", _result);
        }

        public virtual void OnDeserialization(object sender)
        {
            IPersistable[] parents = (IPersistable[]) mInfo.GetValue("Parents", typeof(IPersistable[]));

            foreach (IPersistable persist in parents)
            {
                _parents.Add(persist);
            }

            IPersistable[] children = (IPersistable[]) mInfo.GetValue("Children", typeof(IPersistable[]));

            foreach (IPersistable persist in children)
            {
                _children.Add(persist);
            }

            _result = mInfo.GetValue("Result", typeof(IPersistable)) as IPersistable;

            mInfo = null;
        }
    }
}
